//
//  ProcessedOrderChild.m
//  rrbi
//
//  Created by mac book on 2019/3/21.
//

#import "OrderManagementViewController.h"
#import "OrderManagementCell.h"
#import "FBOrderDetalisViewController.h"
#import "OrderManagementModel.h"
#import "ProcessedOrderSearch.h"
#import "SGTopScrollMenu.h"
#import "DatePickerAlertView.h"
#import "KnightEvaluateViewController.h"

@interface OrderManagementViewController ()<UITableViewDelegate,UITableViewDataSource,SGTopScrollMenuDelegate>

@property (nonatomic, strong) NSMutableArray *mainArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) SGTopScrollMenu *topScrollMenu;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,assign) NSInteger page;
@property (nonatomic, copy) NSString *pass_id;
@property (nonatomic, assign) NSInteger index;

@end

@implementation OrderManagementViewController

- (NSMutableArray *)mainArray {
    if (!_mainArray) {
        _mainArray = [NSMutableArray array];
    }
    return _mainArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(frontDeskRefresh) name:@"FFRONTDeskRefresh" object:nil];
    self.view.backgroundColor = [UIColor whiteColor];
    self.index = 0;
    UIButton *searchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-100, 35)];
    searchButton.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1];
    searchButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [searchButton setTitle:@"搜索订单编号" forState:UIControlStateNormal];
    [searchButton setTitleColor:[UIColor colorWithRed:150.0/255.0 green:150.0/255.0 blue:150.0/255.0 alpha:1] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(searchButtonAction) forControlEvents:UIControlEventTouchUpInside];
    searchButton.layer.cornerRadius = 5;
    searchButton.layer.masksToBounds = YES;
    self.navigationItem.titleView = searchButton;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"日期(1)"] style:UIBarButtonItemStylePlain target:self action:@selector(TimeSelectButtonClick)];
    
    self.startStr = self.endStr = self.pass_id =@"";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT- HitoTopHeight-44-HitoBottomHeight) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderManagementCell class]) bundle:nil] forCellReuseIdentifier:@"orderManagementCell"];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreData)];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    [self.tableView.mj_header beginRefreshing];
    [self RequestData];
    
    
}

- (void)TimeSelectButtonClick {

    [DatePickerAlertView showDatePickerAlertViewWithDateFormat:@"yyyy-MM-dd"
                                                datePickerMode:[@{D_yyyyMMddHHmmss : @(UIDatePickerModeDateAndTime),
                                                                  D_yyyy_MM_dd : @(UIDatePickerModeDate),
                                                                  D_HHmm : @(UIDatePickerModeTime)
                                                                  }[@"yyyy-MM-dd"] integerValue]
                                              selectCompletion:^(NSDate *fromDate, NSDate *toDate) {
                                                  self.startStr = [DatePickerAlertView dateStringWithDate:fromDate format:@"yyyy-MM-dd"];
                                                  self.endStr = [DatePickerAlertView dateStringWithDate:toDate format:@"yyyy-MM-dd"];
                                                  [self.tableView.mj_header beginRefreshing];
                                              }];
}

-(void)searchButtonAction{
    ProcessedOrderSearch *seachVC = [[ProcessedOrderSearch alloc] init];
    [self.navigationController pushViewController:seachVC animated:YES];
}

- (void)frontDeskRefresh {
    [self RequestData];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(!self.Identity.userInfo.isLogin){
        UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:[[Login alloc]init]];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        
        [self RequestData];
        
    }
}

- (void)RequestData {
    
    self.dataArray = [NSMutableArray array];

    [self showHUD];
    NSDictionary* arg = @{@"ince":@"get_order_status",@"sid":[UserModel sharedInstanced].ru_Id, @"uid":self.Identity.userInfo.userID};
    [NetRepositories netConfirm:arg complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
        NSLog(@"===%@",response);
        if(react == NetResponseSuccess){
            [self hidHUD];
            [self.dataArray removeAllObjects];
            
           self.dataArray = [OrderManagementModel mj_objectArrayWithKeyValuesArray:[response objectForKey:@"data"]];
            
            NSMutableArray *arr = [[NSMutableArray alloc]init];
            for (NSInteger i=0; i<self.dataArray.count; i++) {
                OrderManagementModel *model = self.dataArray[i];
                [arr addObject:[NSString stringWithFormat:@"%@(%@)",model.value,model.reminder_num]];
            }
            [self.topScrollMenu removeFromSuperview];
            self.topScrollMenu = [SGTopScrollMenu topScrollMenuWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
            //_topScrollMenu.titlesArr = [NSArray arrayWithArray:arr];
            [_topScrollMenu setTitlesArr:[NSArray arrayWithArray:arr] indexWithMoRen:self.index];
            _topScrollMenu.topScrollMenuDelegate = self;
            [self.view addSubview:_topScrollMenu];
            
            
            if (self.dataArray.count >0) {
                OrderManagementModel *model = self.dataArray[self.index];
                self.pass_id = model.status;
                [self.tableView.mj_header  beginRefreshing];
            }
            
        }else if (react == NetResponseFail){
            [self hidHUD:message];
        }else{
            [self hidHUD:message];
        }
    }];
    
}

- (void)SGTopScrollMenu:(SGTopScrollMenu *)topScrollMenu didSelectTitleAtIndex:(NSInteger)index{
    self.index = index;
    OrderManagementModel *model = self.dataArray[index];
    self.pass_id = model.status;
    [self.tableView.mj_header  beginRefreshing];
    
}

#pragma mark - 数据请求
-(void)getData{
    
    [self getDataWithPageNum:1 isHeader:YES];
}

-(void)getMoreData{
    
    [self getDataWithPageNum:self.page isHeader:NO];
    
}
#pragma mark =====================================================  Data source
- (void)getDataWithPageNum:(NSInteger)pageNum isHeader:(BOOL)isHeader {
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ince":@"get_order_list",
                          @"sid":[UserModel sharedInstanced].ru_Id,
                          @"page":[NSString stringWithFormat:@"%ld",(long)pageNum],
                          @"status":self.pass_id,
                          @"starttime":self.startStr,
                          @"endtime":self.endStr,
                         // @"keyword":self.searchStr
                          };

    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"get_order_list"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if (isHeader) {
            self.page = 1;
            self.tableView.mj_footer.state = MJRefreshStateIdle;
            [self.mainArray removeAllObjects];
        }
        if(flag == 200){
            
            NSMutableArray *tempArr = [NSMutableArray array];
            tempArr = [OrderManagementModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"data"]];
            
            if (isHeader) {
                self.page = 1;
                self.tableView.mj_footer.state = MJRefreshStateIdle;
                [self.mainArray removeAllObjects];
                [self.mainArray addObjectsFromArray:tempArr];
                
                self.page++;
            }else {
                [self.tableView.mj_footer endRefreshing];
                if (tempArr.count > 0) {
                    [self.mainArray addObjectsFromArray:tempArr];
                    self.page++;
                }else{
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
        }else{

            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];

        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        if (isHeader) {
            [self.tableView.mj_header endRefreshing];
            self.page = 1;
        }else {
            [self.tableView.mj_footer endRefreshing];
            self.page--;
        }
        [self hidHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
    }];
    
}

#pragma mark =====================================================  <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.mainArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderManagementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderManagementCell"];
    OrderManagementModel *model = self.mainArray[indexPath.row];
    [cell updataDataWithModel:model];
    __weak typeof(self) weakSelf = self;
    cell.xianQingButtonBlock = ^{
        FBOrderDetalisViewController *vc = [[FBOrderDetalisViewController alloc]init];
        vc.order_id = model.order_id;
        vc.order_type = 2;
        vc.isGuanLi = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.evaluationButtonBlock = ^{
        [weakSelf evaluationButtonClick:model];
    };
    return cell;
}

#pragma mark =====================================================  <UITableViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OrderManagementModel *model = self.mainArray[indexPath.row];
    if (model.delivery.count <= 0) {
        if ([model.pj_status isEqualToString:@"1"]) {//已完成
            return 260;//有评价无骑手
        } else {
            return 220;//没有评价无骑手
        }
    } else {
        if ([model.pj_status isEqualToString:@"1"]) {//已完成
            return 310;//有评价有骑手
        } else {
            return 285;//没有评价有骑手
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

//去评论按钮点击
- (void)evaluationButtonClick:(OrderManagementModel *)model {
    NSString *order_sn= model.order_sn;
    KnightEvaluateViewController *vc= [[KnightEvaluateViewController alloc]init];
    vc.order_sn  = order_sn;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
